<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /*
        1.自定义迭代器-第一版
            -迭代器内部自动调用next()
     */

    class Counter {
        constructor(limit) {
            this.count = 1;
            this.limit = limit;
        }

        next() {
            if (this.count <= this.limit) {
                return {done: false, value: this.count++}
            } else {
                return {done: true, value: undefined}
            }
        }

        [Symbol.iterator]() {
            return this;
        }
    }

    let counter = new Counter(3)
    for (let i of counter) {
        console.log(i)  // 1 2 3   但是
    }
    // fixme:为什么只能被迭代一次
    for (let i of counter) {
        console.log(i)  // 但是只能被迭代一次
    }

    /*
        2.改进版本: 让一个可迭代对象能够创建多个迭代器
     */

    class Counter2 {
        constructor(limit) {
            this.limit = limit
        }

        [Symbol.iterator]() {
            let count = 1, limit = this.limit;
            return {
                next() {
                    if (count <= limit) {
                        return {done: false, value: count++}
                    } else {
                        return {done: true, value: undefined}
                    }
                }
            }
        }
    }

    let counter2 = new Counter2(3)
    for (let i of counter2) {
        console.log(i)      // 1 2 3
    }
    for (let i of counter2) {
        console.log(i)      // 1 2 3
    }
    

</script>
</body>
</html>